package com.glorystone.ins.beanUtils;

import com.glorystone.ins.beanUtils.annotation.ExcelField;
import com.glorystone.ins.common.util.DateEnum;
import com.glorystone.ins.common.util.DateUtils;
import com.glorystone.ins.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Slf4j
public class ExcelUtil {

    public  XSSFWorkbook getXlsxWorkbook(List<String> headers, List<?> datalist, String fileName,int flag) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(fileName);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 10);
        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.size(); i++) {
            XSSFCell cell = row.createCell(i);
            XSSFRichTextString text = new XSSFRichTextString(headers.get(i));
            cell.setCellValue(text);
        }
            int index = 0;
            // 遍历集合数据，产生数据行
            for (int i = 0; i < datalist.size(); i++) {
                index++;
                row = sheet.createRow(index);
                Object object = datalist.get(i);
                Class<?> aClass = object.getClass();
                // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
                Field[] declaredFields = object.getClass().getDeclaredFields();
                if (declaredFields != null) {
                    int columnindex=0;
                    for (int j = 0; j < declaredFields.length; j++) {
                        ExcelField annotation = declaredFields[j].getAnnotation(ExcelField.class);
                        if (annotation != null) {
                            if(flag==2){
                                if (annotation.title() != null && annotation.complete().equals("ok")) {
                                    columnindex = this.operetaBean(declaredFields, aClass, row, columnindex, j, object);
                                }
                            }else if(flag==1){
                                if ((annotation.title() != null && annotation.type() == 1) ||(annotation.title() != null && annotation.completeChannel().equals("ins"))) {
                                    columnindex = this.operetaBean(declaredFields, aClass, row, columnindex, j, object);
                                }
                            }else if(flag==3){
                                if ((annotation.title() != null && annotation.type() == 1 )||(annotation.title() != null && annotation.completeChannel().equals("channel"))) {
                                    columnindex = this.operetaBean(declaredFields, aClass, row, columnindex, j, object);
                                }
                            }else{
                                     columnindex = this.operetaBean(declaredFields, aClass, row, columnindex, j, object);
                            }

                        }
                    }
                }
            }
        return workbook;
        }

        public  void setJspHeader(HttpServletRequest request,HttpServletResponse response, Object object,List<?> orderList,String excelName,String fileName,int flag){
                List<String> stringStringMap = new BeanUtils().operateBeans(object,flag);
                XSSFWorkbook workbook = this.getXlsxWorkbook(stringStringMap, orderList, excelName,flag);
                //String fileName = "保险公司对账数据导出 " + DateUtils.dateToStr(new Date(), DateEnum.DATE_BANK_SEQ);
                response.reset();
                try {
                    //导出支持中文名，兼容IE、火狐
                    if (request.getHeader("user-agent").indexOf("MSIE") != -1) {
                        fileName = java.net.URLEncoder.encode(fileName, "utf-8") + ".xlsx";
                    } else {
                        fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1") + ".xlsx";
                    }
                    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                    workbook.write(response.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }


        public int operetaBean(Field[] declaredFields, Class<?> aClass,XSSFRow row,int columnindex,int j,Object object ){
            XSSFCell cell = row.createCell(columnindex++);
            log.info("columnindex"+columnindex+"j"+j);
            String name = declaredFields[j].getName();
            String methodname = name.substring(0, 1).toUpperCase() + name.substring(1);
            String gettername = "get" + methodname;
            try {
                Method getmethod = aClass.getMethod(gettername);
                Object value = getmethod.invoke(object);
                if(StringUtils.isBlank(value+"")){
                    XSSFRichTextString richString = new XSSFRichTextString("");
                    cell.setCellValue(richString);
                }else if("null".equals(value+"")){
                    XSSFRichTextString richString = new XSSFRichTextString("");
                    cell.setCellValue(richString);
                }else if("undefined".equals(value+"")){
                    XSSFRichTextString richString = new XSSFRichTextString("");
                    cell.setCellValue(richString);
                }else {
                    XSSFRichTextString richString = new XSSFRichTextString(value+"");
                    cell.setCellValue(richString);
                }

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return columnindex;
        }

}
